﻿using FlyingEye.DeviceMaintenance;
using FlyingEye.DeviceMaintenance.Repositories;
using FlyingEye.Exceptions;
using Volo.Abp.Application.Services;

namespace FlyingEye.DeviceMaintenanceServices
{
    /// <summary>
    /// 校验项服务
    /// </summary>
    public class DevicePartCheckedResultService : ApplicationService
    {
        private readonly IDevicePartCheckedResultRepository _checkedResultRepository;

        public DevicePartCheckedResultService(IDevicePartCheckedResultRepository checkedResultRepository)
        {
            _checkedResultRepository = checkedResultRepository;
        }

        /// <summary>
        /// 获取所有校验项
        /// </summary>
        public async Task<List<DevicePartCheckedResultResponse>> GetListByRecordAsync(Guid recordId)
        {
            var list = await _checkedResultRepository.GetListAsync(item => item.MaintenanceRecordId == recordId);

            if (!list.Any())
            {
                return new(0);
            }

            return ObjectMapper.Map<List<DevicePartCheckedResultModel>, List<DevicePartCheckedResultResponse>>(list);
        }

        /// <summary>
        /// 通过校验项
        /// </summary>
        public async Task PassCheckItemAsync(Guid id)
        {
            var model = await _checkedResultRepository.FindAsync(id);

            if (model == null)
            {
                throw new ResourceNotFoundException($"校验项[{id}]不存在。");
            }

            model.IsPassed = true;

            await _checkedResultRepository.UpdateAsync(model);
        }

        /// <summary>
        /// 不通过校验项
        /// </summary>
        public async Task FailCheckItemAsync(Guid id)
        {
            var model = await _checkedResultRepository.FindAsync(id);

            if (model == null)
            {
                throw new ResourceNotFoundException($"校验项[{id}]不存在。");
            }

            model.IsPassed = false;

            await _checkedResultRepository.UpdateAsync(model);
        }
    }
}
